<template>
  <div>
    <!-- 加载动画 -->
    <div v-if="isLoading" class="flex justify-center items-center py-12 animate-fade-in">
      <LoadingAnimation />
    </div>
    
    <!-- 装饰元素 -->
    <div class="absolute top-20 left-10 w-32 h-32 rounded-full bg-gradient-to-r from-indigo-500/10 to-purple-500/10 blur-3xl pointer-events-none"></div>
    <div class="absolute bottom-20 right-10 w-40 h-40 rounded-full bg-gradient-to-r from-blue-500/10 to-indigo-500/10 blur-3xl pointer-events-none"></div>
    
    <!-- 装饰性图标 -->
    <div class="absolute top-10 right-20 opacity-30 pointer-events-none">
      <DecorativeIcon type="star" />
    </div>
    <div class="absolute bottom-10 left-20 opacity-30 pointer-events-none">
      <DecorativeIcon type="lightning" />
    </div>
    <div class="absolute top-1/2 left-5 opacity-30 pointer-events-none">
      <DecorativeIcon type="news" />
    </div>
    <div class="absolute top-1/3 right-5 opacity-30 pointer-events-none">
      <DecorativeIcon type="dot" />
    </div>
    
    <div v-if="!isLoading" class="animate-fade-in">
      <el-breadcrumb separator="/" class="mb-4">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>{{ sourceName }}</el-breadcrumb-item>
      </el-breadcrumb>

      <el-card class="source-header-card mb-6">
        <template #header>
          <div class="flex justify-between items-center relative">
            <div class="absolute -left-2 -top-2 w-8 h-8 rounded-full bg-indigo-500 opacity-10 blur-md"></div>
            <div class="absolute -right-1 -top-1 scale-75 opacity-50 pointer-events-none">
              <DecorativeIcon type="star" :animate="false" />
            </div>
            <h2 class="text-2xl font-bold m-0 source-title">{{ sourceName }}</h2>
            <span class="text-indigo-500 font-medium">共 {{ sourceNews.length }} 条新闻</span>
          </div>
        </template>
      </el-card>

      <el-row :gutter="20" class="animate-slide-up">
        <el-col v-for="(news, index) in sourceNews" :key="news.id" :xs="24" :sm="12" :lg="8" class="mb-4" :style="{'animation-delay': index * 0.05 + 's'}">
          <el-card shadow="hover" class="news-card h-full">
            <div class="relative">
              <div class="absolute -right-2 -top-2 w-8 h-8 rounded-full bg-indigo-500 opacity-10 blur-md"></div>
              <h3 class="text-lg font-semibold mb-2 line-clamp-2 news-title hover-effect">{{ news.title }}</h3>
              <p class="text-gray-600 text-sm mb-3 line-clamp-3">{{ news.summary }}</p>
                              <div class="flex justify-between items-center text-xs text-gray-500">
                <span>{{ formatDate(news.publishTime) }}</span>
                <a :href="`/news/${news.id}`" target="_blank" class="read-more-link">
                  阅读全文
                </a>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

              <div v-if="sourceNews.length === 0" class="text-center py-8 text-gray-500 empty-state">
        <div class="mb-4 opacity-50">
          <DecorativeIcon type="news" :animate="false" />
        </div>
        <p>暂无新闻</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, inject, onMounted, watch } from 'vue'
import { sourceAPI, newsAPI } from '~/services/api'
import LoadingAnimation from '~/components/LoadingAnimation.vue'
import DecorativeIcon from '~/components/DecorativeIcon.vue'

const route = useRoute()
const sourceId = parseInt(route.params.id)

// 获取分类筛选状态
const activeCategory = inject('activeCategory', ref('all'))
const isLoading = ref(true)
const sourceData = ref({})
const sourceNews = ref([])
const categories = ref([])

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取分类ID
const getCategoryId = (categoryKey) => {
  if (categoryKey === 'all') return null
  // 优先 code，其次 id
  const category = categories.value.find(cat => cat.code === categoryKey || String(cat.id) === String(categoryKey))
  return category ? category.id : null
}

// 加载信源信息
const loadSourceData = async () => {
  try {
    const sources = await sourceAPI.getSources()
    const source = sources.find(s => s.id === sourceId)
    if (source) {
      sourceData.value = source
    } else {
      // 信源不存在，重定向到首页
      navigateTo('/')
      return
    }
  } catch (error) {
    console.error('加载信源信息失败:', error)
    navigateTo('/')
  }
}

// 加载新闻数据
const loadNewsData = async () => {
  try {
    const categoryId = getCategoryId(activeCategory.value)
    const params = { limit: 50 } // 获取更多新闻用于展示
    if (categoryId) {
      params.categoryId = categoryId
    }
    
    const newsData = await newsAPI.getNewsBySource(sourceId, params)
    sourceNews.value = newsData
  } catch (error) {
    console.error('加载新闻数据失败:', error)
    sourceNews.value = []
  }
}

// 加载分类数据
const loadCategories = async () => {
  try {
    categories.value = await sourceAPI.getCategories()
  } catch (error) {
    console.error('加载分类数据失败:', error)
  }
}

// 初始化数据
const initData = async () => {
  try {
    isLoading.value = true
    await Promise.all([
      loadSourceData(),
      loadCategories()
    ])
    await loadNewsData()
  } catch (error) {
    console.error('初始化数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 监听分类变化
watch(activeCategory, () => {
  loadNewsData()
})

// 计算属性
const sourceName = computed(() => sourceData.value?.name || '未知信源')

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.animate-fade-in {
  animation: fadeIn 0.5s ease-out;
}

.animate-slide-up {
  animation: slideUp 0.5s ease-out;
}

/* 卡片样式 */
.source-header-card {
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.news-card {
  transition: all 0.3s ease;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transform: translateY(0);
}

.news-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

/* 深色模式适配 */


/* 标题样式 */
.source-title {
  position: relative;
  display: inline-block;
  color: var(--primary-color);
  transition: all 0.3s ease;
}


/* 新闻标题悬停效果 */
.news-title.hover-effect {
  position: relative;
  display: inline-block;
  transition: all 0.3s ease;
}

.news-title.hover-effect:hover {
  color: var(--primary-color);
}

.news-title.hover-effect::after {
  content: '';
  position: absolute;
  width: 0;
  height: 2px;
  bottom: -2px;
  left: 0;
  background-color: var(--primary-color);
  transition: width 0.3s ease;
}

.news-title.hover-effect:hover::after {
  width: 100%;
}



/* 阅读更多链接 */
.read-more-link {
  color: var(--primary-color);
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  padding: 2px 4px;
  border-radius: 4px;
}

.read-more-link:hover {
  color: var(--primary-hover);
  background-color: rgba(var(--primary-rgb), 0.1);
}



/* 空状态样式 */
.empty-state {
  transition: all 0.3s ease;
  padding: 2rem;
  border-radius: 12px;
  background-color: rgba(0, 0, 0, 0.02);
}

</style>